<template>
	<ul class = "list" >
		<li 
			v-for = "item of letters" 
			:key = "item" 
			:ref = "item"
			@click = "handleClick(item)"
			@touchstart.prevent = "handleTouchStart"
			@touchmove = "handleTouchMove"
			@touchend = "handleTouchEnd"
		>{{item}}</li>
	</ul>
</template>
<script>
	export default {
		name : 'alphabet',
		props : ["cities"],
		data () {
			return {
				touchStatus : false,
				startY:0,
				timer:null
			}
		},
		updated () {
			// 组件重新获取数据，加载后执行的生命函数
			this.startY = this.$refs["A"][0].offsetTop; //获取A字母距顶部的距离
		},
		computed: {
			letters () {
				const letter = [];
				for(let i in this.cities){
					letter.push(i)
				}
				return letter;
			}
		},
		methods:{
			handleClick (key) {
				this.$emit("change",key);
			},
			handleTouchStart () {
				this.touchStatus = true;
			},
			handleTouchMove (e) {
				if(this.touchStatus){
					if(this.timer){
						clearTimeout(this.timer);
					}
					this.timer = setTimeout(() => {
						const touchY = e.touches[0].clientY-79; //获取滑动位置距顶部的距离
						const index = Math.floor((touchY-this.startY)/ 20);//距离差/字母高度 获取字母索引
						if(index >= 0 && index <this.letters.length){
							this.$emit("change",this.letters[index]);
						}
					},16)
				}
			},
			handleTouchEnd () {
				this.touchStatus = false; 
			},
		}
	}
</script>
<style scoped lang = "less">
	@import '~css/variable.less';
	.list {
		width:.4rem;
		display: flex;
		flex-direction:column;
		justify-content: center;
		position: absolute;
		top:1.58rem;
		right:0;
		bottom:0;
		li {
			line-height:.4rem;
			color:@bgColor;
			text-align: center;
		}
	}
</style>